
import util.TabelaHost;
import util.TabelaRoteadores;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import util.PersonalizarJFrame;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Servidor.java
 *
 * Created on 21/10/2011, 14:17:00
 */
/**
 *
 * @author Cleiton
 */
public class ServidorJanela extends javax.swing.JFrame {

    private PersonalizarJFrame personalizarJFrame;
    private Servidor servidor;
    private TabelaRoteadores tabelaRoteadores;
    private TabelaHost tabelaHost;
    private boolean alterarRede = false;
    private ArrayList<String> caminhoPercorrido;
    private Desenho desenho = new Desenho();
    private String[][] hosts;
    String[][] rede;

    /** Creates new form Servidor */
    public ServidorJanela() {
        personalizarJFrame = new PersonalizarJFrame(this);
        personalizarJFrame.setLookFeel();
        initComponents();
        instanciarObjetoRmi();
        personalizarJFrame.setPositionRElative();
        tabelaRoteadores = new TabelaRoteadores(jTable1);
        tabelaHost = new TabelaHost(jTable2);
        caminhoPercorrido = new ArrayList<String>();
    }

    /**
     * Inicializa para que o servidor fique recebendo ligações Rmi de hosts e Roteadores
     */
    public void instanciarObjetoRmi() {

        try {
            servidor = new Servidor() {

                @Override
                void redesenharTableRoteador(String name) {
                    tabelaRoteadores.adicionarRoteador(name);
                }

                @Override
                void redesenharTableHost(String name) {
                    tabelaHost.adicionarHost(name);
                }

                @Override
                public void atualizarCaminho(String origem, String destino) throws RemoteException {
                    if (caminhoPercorrido.isEmpty()) {
                        caminhoPercorrido.add(origem);
                    }
                    caminhoPercorrido.add(destino);
                    System.out.print("Caminho percorrido = ");
                    for (String string : caminhoPercorrido) {
                        System.out.print(string);
                    }
                    desenho.RefazJanela();
                    desenho.cria_desenho_rede(rede, hosts, caminhoPercorrido);
                    desenho.setVisible(true);
                }
            };

            Naming.rebind("rmi://" + HostImpl.SERVIDORCENTRAL + "/Servidor", servidor);

        } catch (RemoteException ex) {
            Logger.getLogger(ServidorJanela.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(ServidorJanela.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jrbDjikstra = new javax.swing.JRadioButton();
        jrbBellman = new javax.swing.JRadioButton();
        jbtAlterarRede = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("GERENCIADOR SUPREMO");

        jLabel1.setText("ROTEADORES");

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        jLabel2.setText("HOST LIGAR GATEWAY");

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Host", "Roteador"
            }
        ) {

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                if(columnIndex==0)
                return false;
                return true;
            }
        });
        jScrollPane2.setViewportView(jTable2);

        jButton1.setText("Salvar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Limpar Telas");
        jButton2.setToolTipText("Limpa todos os Roteadores.");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nome"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                if(columnIndex==0 || rowIndex==columnIndex-1)
                return false;

                return true;
            }

        });
        jScrollPane1.setViewportView(jTable1);

        buttonGroup1.add(jrbDjikstra);
        jrbDjikstra.setSelected(true);
        jrbDjikstra.setText("Djikstra");
        jrbDjikstra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbDjikstraActionPerformed(evt);
            }
        });

        buttonGroup1.add(jrbBellman);
        jrbBellman.setText("BellMan - Ford");
        jrbBellman.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbBellmanActionPerformed(evt);
            }
        });

        jbtAlterarRede.setText("Alternar Algoritmo");
        jbtAlterarRede.setToolTipText("Altera o Algoritmo deRoteamento");
        jbtAlterarRede.setEnabled(false);
        jbtAlterarRede.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAlterarRedeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jrbDjikstra)
                        .addComponent(jrbBellman))
                    .addComponent(jbtAlterarRede))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
                        .addGap(2, 2, 2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jrbDjikstra)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jrbBellman)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jbtAlterarRede)
                .addContainerGap(318, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Configurar Rede", jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 939, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        rede = tabelaRoteadores.getRede();
        hosts = this.tabela_hosts();
        servidor.setRede(rede);
        servidor.setHostGatway(tabelaHost.getLigacaoGatways());
        if (jrbBellman.isSelected()) {
            servidor.enviarRede(alterarRede, true);
        } else {
            servidor.enviarRede(alterarRede, false);
        }
        alterarRede = true;
        desenho.cria_desenho_rede(rede, hosts, caminhoPercorrido);
        JOptionPane.showMessageDialog(rootPane, "A rede esta Configurada.\nPode começar a brincadeira");
        desenho.setVisible(true);
        jbtAlterarRede.setEnabled(true);
}//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            caminhoPercorrido = new ArrayList<String>();
            servidor.limparrede();
            desenho.RefazJanela();
            desenho.cria_desenho_rede(rede, hosts, caminhoPercorrido);
            desenho.setVisible(true);
        } catch (RemoteException ex) {
            Logger.getLogger(ServidorJanela.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_jButton2ActionPerformed

    private void jrbDjikstraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbDjikstraActionPerformed
    }//GEN-LAST:event_jrbDjikstraActionPerformed

    private void jrbBellmanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbBellmanActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jrbBellmanActionPerformed

    private void jbtAlterarRedeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAlterarRedeActionPerformed
        try {
            servidor.alterarAlgoritmo(alterarRede);
        } catch (RemoteException ex) {
            Logger.getLogger(ServidorJanela.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jbtAlterarRedeActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ServidorJanela().setVisible(true);
            }
        });
    }

    private String[][] tabela_hosts() {
        String[][] hosts = new String[jTable2.getRowCount()][2];
        for (int i = 0; i < jTable2.getRowCount(); i++) {
            hosts[i][0] = (String) jTable2.getValueAt(i, 0);
            hosts[i][1] = (String) jTable2.getValueAt(i, 1);
        }
        return hosts;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JButton jbtAlterarRede;
    private javax.swing.JRadioButton jrbBellman;
    private javax.swing.JRadioButton jrbDjikstra;
    // End of variables declaration//GEN-END:variables
}
